<template>
  <el-row>
    <el-col :span="24">
      <el-form :model="userInfo" :rules="rules" ref="userForm">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="userInfo.mobile"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="photoUrl">
          <el-upload
            ref="upload"
            action=""
            list-type="picture-card"
            :before-upload="imageConvertoBase64"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :auto-upload="true"
            :file-list="headImage"
            :on-exceed="handleExceed"
            :http-request="handleConverting"
            :limit="1"
            accept="image/jpg,image/jpeg,image/png"
            >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="权限" prop="appIds">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" :disabled="userInfo.role === 'ADMIN' ? true : false" @change="handleCheckAllChange">全选</el-checkbox>
            <el-checkbox-group v-model="userInfo.appIds" size="small" :disabled="userInfo.role === 'ADMIN' ? true : false" @change="handleCheckedAppidsChange">
              <el-checkbox v-for="item in publicList" :date-appid="item.appId" :key="item.appId" :label="item.appId" name="appIds">{{item.publicAccountNickname}}</el-checkbox>
            </el-checkbox-group>
        </el-form-item>
        <div class="line"></div>
        <el-form-item class="btn-box">
          <el-button @click="back">返回</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>
import util from '../../util/index';
import auth from '../../util/auth';
import cookie from '../../lib/cookie';
import CONSTANT from '../../constant/common';

export default {
  data() {
    const editUserInfo = this.$store.state.user.userObj.editUser;
    const publicAccountsList = this.$store.state.user.userObj.editUser
      .publicAccounts.map(item => item.appId);
    return {
      checkAll: false,
      isIndeterminate: false,
      dialogImageUrl: '',
      dialogImage: '',
      dialogVisible: false,
      rules: {
        nickname: [
          {
            required: true, message: '请输入名称', trigger: 'blur',
          },
        ],
        username: [
          {
            required: true, message: '请输入用户名字', trigger: 'blur',
          },
          {
            min: 6, max: 30, message: '长度到6-30个字符', trigger: 'blur',
          },
          {
            validator(rule, value, callback) {
              if (value.match(/[\u4e00-\u9fa5]/g)) {
                callback(new Error('请勿输入中文'));
              } else {
                callback();
              }
            },
          },
        ],
        mobile: [
          {
            required: true, message: '请输入电话', trigger: 'blur',
          },
          { pattern: /^1[345789]\d{9}$/g, message: '请输入正确的电话', trigger: 'blur' },
        ],
        appIds: [
          {
            type: 'array', required: true, message: '请至少选择一个公众号', trigger: 'change',
          },
        ],
      },
      userInfo: {
        id: editUserInfo.id || '',
        nickname: editUserInfo.nickname || '',
        username: editUserInfo.username || '',
        mobile: editUserInfo.mobile || '',
        role: editUserInfo.role || '',
        imageData: editUserInfo.imageData || '',
        // photoUrl: editUserInfo.photoUrl || '',
        appIds: publicAccountsList || [],
      },
    };
  },
  computed: {
    // form() {
    //   return this.$store.state.user.userObj.editUser || {};
    // },
    publicList() {
      const ret = this.$store.state.user.publicList;
      return ret || [];
    },
    appidArr() {
      const ret = this.$store.state.user.publicList;
      const newPL = [];
      ret.map(item => newPL.push(item.appId));
      return newPL || [];
    },
    headImage() {
      const editUserInfo = this.$store.state.user.userObj.editUser;
      return editUserInfo && editUserInfo.imageData ? [{ url: editUserInfo.imageData }] : [];
    },
  },
  methods: {
    handleCheckAllChange(val) {
      this.userInfo.appIds = val ? this.appidArr : [];
      this.isIndeterminate = false;
    },
    handleCheckedAppidsChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.appidArr.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.appidArr.length;
    },
    checkPublicAccount(appId) {
      if (!(appId instanceof Array)) return false;
      const mark = this.userInfo.appIds.indexOf(appId) !== -1;
      return mark;
    },
    back() {
      this.$router.push({
        path: '/user',
      });
    },
    handleConverting(...arg) {
      console.log(arg);
    },
    imageConvertoBase64(file) {
      util.imageConvertoBase64(file).then((base64) => {
        this.userInfo.imageData = base64;
      }).catch((e) => {
        console.log('convert to base64 error .', e);
      });
    },
    submit() {
      // this.$refs.upload.submit();
      // util.imageConvertoBase64(this.dialogImage).then((base64) => {
      //   this.userInfo.imageData = base64;
      this.$refs.userForm.validate().then(() => {
        if (this.$route.path.indexOf('add') > 0) {
          this.$store.dispatch('addUser', this.userInfo).then(() => {
            this.$refs.userForm.resetFields();
            this.$refs.upload.clearFiles();
            this.$message.success('创建账号成功!');
            this.$router.push({
              path: '/user',
            });
          }, (err) => {
            this.$message.error(err.message);
          });
        } else {
          this.$store.dispatch('editUser', this.userInfo).then(() => {
            this.$store.dispatch('getUserDetail', {
              userId: this.userInfo.id,
            }).then((res) => {
              if (res.id === cookie(CONSTANT.COOKIE_USER_ID)) {
                auth.saveUserInfo(res, false);
                this.$store.dispatch('setLoginInfo', res);
              }
              this.$refs.userForm.resetFields();
              this.$refs.upload.clearFiles();
              this.$message.success('修改信息成功');
              this.$router.push({
                path: '/user',
              });
            });
          });
        }
      });
      // });
      // console.log(this.userInfo);
    },
    handleExceed() {
      this.$message.warning('请先删除原来的头像图片');
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    getPublicAccounts() {
      this.$store.dispatch('getWoaList');
    },
  },
  mounted() {
    this.getPublicAccounts();
  },
};
</script>
<style lang="less" scoped>
.detail {
  .title {
    line-height: 60px;
  }
}
.btn-box {
    text-align: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

